package com.tool.util;

import com.tool.bean.TableGenInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringBufferInputStream;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class MybatisMappingUtil
{
  private static transient Log log = LogFactory.getLog(MybatisMappingUtil.class);

  private static final EntityResolver entityResolver = new EntityResolver()
  {
    public InputSource resolveEntity(String publicId, String systemId)
      throws SAXException, IOException
    {
      InputSource is = new InputSource(new StringBufferInputStream(""));
      is.setPublicId(publicId);
      is.setSystemId(systemId);
      return is;
    }
  };

  public static void addMapping(TableGenInfo info)
  {
    String resKey = info.getPackageName().replaceAll("\\.", "/") + "/dao/" + 
      StringUtil.getBeanName(info.getTableName()) + "DAOMapper.xml";
    String mapPath = ConfigUtil.getProperty("mybatis.file");
    String realPath = mapPath.replace("${ds}", info.getDsName());
    if (log.isDebugEnabled())
    {
      log.debug("------------------------------------");
      log.debug("数据源映射键名:" + resKey);
      log.debug("映射文件具体路径:" + realPath);
      log.debug("------------------------------------");
    }

    SAXReader reader = new SAXReader();
    reader.setEntityResolver(entityResolver);
    try
    {
      Document doc = reader.read(new File(realPath));
      List list = doc.selectNodes("configuration/mappers/mapper[@resource='" + resKey + "']");
      if ((list != null) && (list.size() > 0))
      {
        if (log.isDebugEnabled())
        {
          log.debug("------------------------------------");
          log.debug("数据源映射文件存在相应的键名:" + resKey + ",取消添加");
          log.debug("------------------------------------");
        }
        return;
      }
      if (log.isDebugEnabled())
      {
        log.debug("------------------------------------");
        log.debug("数据源映射文件不存在相应的键名:" + resKey + ",开始添加");
        log.debug("------------------------------------");
      }
      long startTime = System.currentTimeMillis();

      Element elem = (Element)doc.selectSingleNode("configuration/mappers");
      Element e = elem.addElement("mapper");
      e.addAttribute("resource", resKey);
      XMLWriter writer = new XMLWriter(new FileOutputStream(realPath), OutputFormat.createPrettyPrint());
      writer.write(doc);
      writer.close();
      long endTime = System.currentTimeMillis();
      if (log.isDebugEnabled())
      {
        log.debug("------------------------------------");
        log.debug("添加结束,耗时:" + (endTime - startTime) + "毫秒");
        log.debug("------------------------------------");
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}